import { instanceParamsType, ObjectStorageType } from '../type';

export function initFactor(params: instanceParamsType): any {
  const { sdkOtherParams = {} } = params;
  let instance: any;
  if (!params.type) {
    throw new Error('请选择需上传的对象存储类型');
  }
  switch (params.type) {
    case ObjectStorageType.NORMAL:
      break;
    case ObjectStorageType.OBS:
      if (!params.sdkObject) throw new Error('未传入obs skd库');
      if (!params.endPoint) throw new Error('未传入endpoint');
      if (!params.bucketName) throw new Error('未传入bucketName');
      let obsParams: any = {
        ...sdkOtherParams,
        access_key_id: params.accessKey,
        secret_access_key: params.secretKey,
        server: params.endPoint,
      };
      // 存在sts
      if (params.securityToken) obsParams.security_token = params.securityToken;
      instance = new params.sdkObject(obsParams);
      break;
    case ObjectStorageType.OSS:
      if (!params.sdkObject) throw new Error('未传入oss skd库');
      if (!params.endPoint) throw new Error('未传入endpoint');
      if (!params.bucketName) throw new Error('未传入bucketName');
      let ossParams: any = {
        ...sdkOtherParams,
        accessKeyId: params.accessKey,
        accessKeySecret: params.secretKey,
        authorizationV4: true,
        endpoint: params.endPoint,
        bucket: params.bucketName,
      };
      // 未传入region，从endPoint中取
      if (!params.region) {
        const ossRegionReg = /https?:\/\/([a-zA-Z0-9-]+)\.aliyuncs\.com/;
        const match = params.endPoint.match(ossRegionReg);
        if (match && match[1]) {
          params.region = match[1];
        } else {
          throw new Error('未解析出region');
        }
      } else {
        ossParams.region = params.region;
      }
      // 存在sts
      if (params.securityToken) ossParams.stsToken = params.securityToken;
      instance = new params.sdkObject(ossParams);
      break;
    // minio aws全部采用aws库  todo sdk采用V2版本
    case ObjectStorageType.MINIO:
    case ObjectStorageType.AWS:
      if (!params.sdkObject) throw new Error('未传入aws v2 skd库');
      let S3Params: any = {
        ...sdkOtherParams,
        accessKeyId: params.accessKey,
        secretAccessKey: params.secretKey,
        endpoint: params.endPoint,
        s3ForcePathStyle: params.type === ObjectStorageType.MINIO ? true : null,
        signatureVersion: 'v4',
      };
      if (params.securityToken) S3Params.sessionToken = params.securityToken;
      params.sdkObject.config.update(S3Params);
      instance = new params.sdkObject.S3({});
      break;
  }
  return instance;
}
